package oleg; 

/**
 * Copyright 2008,2009 Oleg Frenkel
 *
 * This file is part of PerfectSearch.
 *
 * PerfectSearch is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PerfectSearch is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PerfectSearch.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.pim.*;

import oleg.images.ImageManager;
import oleg.locale.LocaleManager;

public class ContactView
{
  private MainSearch mainSearch;
  private ContactUtils contUtils = new ContactUtils();

  private List phonesList = new List("", List.IMPLICIT);
  private Vector phones;
  private Vector phonesAttributes = new Vector();
  private Display display;
  private Displayable prevScreen;

  private Command backCommand = new Command("Back", Command.BACK, 2);
  private Command callCommand = new Command("Call", Command.ITEM, 1);
  private Command exitCommand = new Command("Exit", Command.EXIT, 3);

  public ContactView(MainSearch mainSearch) {
    this.mainSearch = mainSearch;
    display = Display.getDisplay(mainSearch);

    phonesList.setFitPolicy(Choice.TEXT_WRAP_ON);

    phonesList.addCommand(backCommand);
    phonesList.setSelectCommand(callCommand);
    phonesList.addCommand(exitCommand);

    phonesList.setCommandListener(new ViewCommandListener());
  }

  public void updateInterface() {
    phonesList.removeCommand(backCommand);
    phonesList.removeCommand(callCommand);
    phonesList.removeCommand(exitCommand);

    LocaleManager localeMgr = LocaleManager.instance();

    callCommand = new Command(localeMgr.getProperty(C.CALL), Command.ITEM, 1);
    backCommand = new Command(localeMgr.getProperty(C.BACK), Command.BACK, 2);
    exitCommand = new Command(localeMgr.getProperty(C.EXIT), Command.ITEM, 3);

    phonesList.addCommand(backCommand);
    phonesList.addCommand(exitCommand);
    phonesList.setSelectCommand(callCommand);
  }

  public void showDetail(Contact selCont) {
    String contactName = selCont.getString(Contact.FORMATTED_NAME, 0);
    String listName = selCont.getPIMList().getName();
    phonesList.setTitle(contactName + " [" + listName + "]");
    phonesList.deleteAll();

    phonesAttributes.removeAllElements();
    phones = contUtils.getValuesAsVector(selCont, Contact.TEL, phonesAttributes);
    for (int i = 0; i < phones.size(); i++) {
      String curPhone = (String)phones.elementAt(i);
      Image curPhoneImg = (Image)phonesAttributes.elementAt(i);
      phonesList.append(getPretty(curPhone), curPhoneImg);
    }

    Vector addrValues = contUtils.getValuesAsVector(selCont, Contact.FORMATTED_ADDR);
    for (int i = 0; i < addrValues.size(); i++) {
      phonesList.append((String)addrValues.elementAt(i), null);
    }

    int[] allFields = selCont.getPIMList().getSupportedFields();
    for (int j = 0; j < allFields.length; j++) {
      int curField = allFields[j];
      if (curField == Contact.TEL ||
          curField == Contact.FORMATTED_NAME ||
          curField == Contact.ADDR ||
          curField == Contact.ADDR_COUNTRY ||
          curField == Contact.ADDR_EXTRA ||
          curField == Contact.ADDR_LOCALITY ||
          curField == Contact.ADDR_POBOX ||
          curField == Contact.ADDR_POSTALCODE ||
          curField == Contact.ADDR_REGION ||
          curField == Contact.ADDR_STREET ||
          curField == Contact.FORMATTED_ADDR ||
          curField == Contact.NAME ||
          curField == Contact.NAME_FAMILY ||
          curField == Contact.NAME_GIVEN ||
          curField == Contact.NAME_OTHER ||
          curField == Contact.NAME_PREFIX ||
          curField == Contact.NAME_SUFFIX ||
          curField == Contact.UID) {
        continue;
      }

//       oleg.log.Logger.log("ContactView: Adding field: " + curField);
      Vector values = contUtils.getValuesAsVector(selCont, curField);
      for (int i = 0; i < values.size(); i++) {
        phonesList.append((String)values.elementAt(i), null);
      }
    }

    prevScreen = display.getCurrent();
    display.setCurrent(phonesList);
  }

  private String getPretty(String telNum) {
    StringBuffer prettyTelNum = new StringBuffer();
    int curStartIndex = 0;
    int firstSpace = (telNum.length() - 4) % 3;
    if (firstSpace > 0) {
      prettyTelNum.append(telNum.substring(curStartIndex, firstSpace));
      prettyTelNum.append(" ");
      curStartIndex = firstSpace;
    }

    while (curStartIndex + 4 < telNum.length()) {
      prettyTelNum.append(telNum.substring(curStartIndex, curStartIndex + 3));
      prettyTelNum.append(" ");
      curStartIndex = curStartIndex + 3;
    }

    prettyTelNum.append(telNum.substring(curStartIndex));

    return prettyTelNum.toString();
  }

  private void callSelectedNumber() {
    if (phonesList.getSelectedIndex() >= phones.size()) {
//       Alert alert = new Alert(localeMgr.getProperty(C.SELECT_PHONE_NUMBER));
//       alert.setString(localeMgr.getProperty(C.PLEASE_SELECT_PHONE_NUMBER));
      return;
    }
    String telStr = (String)phones.elementAt(phonesList.getSelectedIndex());
    try {
      boolean res = mainSearch.platformRequest("tel:" + telStr);
      if (res) {
        // there are no resources in the device: midlet has to exit in order 
        // to place a call
        mainSearch.exitApplication();
        return;
      }
    } catch (Exception e) {
      throw new RuntimeException("Failed to call: " + e.getMessage());
    }

  }

  private class ViewCommandListener implements CommandListener
  {
    public void commandAction(Command c, Displayable s) {
      if (c == exitCommand) {
        mainSearch.exitApplication();
        return;
      }

      if (c == backCommand) {
        display.setCurrent(prevScreen);
        return;
      }

      if (c == callCommand) {
        callSelectedNumber();
        return;
      }
    }
  }
}
